<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Log;
use think\Db;

/**
 * TG ROBOT
 *
 */
class Tgbot extends Frontend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $auth = null;
    protected $layout = null;
    public $robotToken;

    public function _initialize()
    {
        parent::_initialize();
        $config = get_addon_config('tgbot');
        if(!empty($config['robottokens'])){
            $tokens = explode("\r\n",$config['robottokens']);
            $this->robotToken = $tokens;
        }
    }

    /**
     * getHookInfo
     */
    public function getHookInfo(){
        $res = array();
        $config = get_addon_config('tgbot');
        if(count($this->robotToken)){
            foreach($this->robotToken as $k => $v){
                $bot = new \TelegramBot\Api\BotApi($v);
                $result = $bot->getWebhookInfo();
                array_push($res,$result);
            }
        }
        dump($res);
    }

    /**
     * Tg回调
     */
    public function receive(){
        Log::init([
            'type'  =>  'File',
            'path'  =>  RUNTIME_PATH . 'tgbot/',
        ]);
        $input = file_get_contents('php://input');
        $input = json_decode($input, true);
        Log::record($input, 'info');
        $config = get_addon_config('tgbot');
        if(!empty($config['instruct'])){
            $instructs = str_replace('，',',',$config['instruct']);
            $instructs = explode(',',$instructs);
            if (isset($input['message'])) {
                if (isset($input['message']['text'])) {
                    $msg = $input['message']['text'];
                    foreach($instructs as $k => $v){
                        if(strpos($msg, $v) !== false){
                            foreach($this->robotToken as $k1 => $v1){
                                $bot = new \TelegramBot\Api\BotApi($v1);
                                $bot->sendMessage($input['message']['chat']['id'], $msg);
                            }
                        }
                    }
                }
            }else if(isset($input['my_chat_member'])){
                if (isset($input['my_chat_member']['text'])) {
                    $msg = $input['my_chat_member']['text'];
                    foreach($instructs as $k => $v){
                        if(strpos($msg, $v) !== false){
                            foreach($this->robotToken as $k1 => $v1){
                                $bot = new \TelegramBot\Api\BotApi($v1);
                                $bot->sendMessage($input['my_chat_member']['chat']['id'], $msg);
                            }
                        }
                    }
                }
            }
        }
        $this->success('ok');
    }
}
